package com.stone.common.action;

/**
 * <pre>
 * 附件管理
 * </pre>
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import com.stone.common.pojo.TFile;
import com.stone.common.service.FileService;
import com.stone.para.IConstant;
import com.stone.sys.pojo.TUser;
import com.stone.utils.DateFormatTool;
import com.stone.utils.FileUtils;
import com.stone.utils.Resources;

import frm.ssh.action.BaseAction;
import frm.ssh.exception.AppException;

public class FileAction extends BaseAction {

	private static final long serialVersionUID = 3979577965804736350L;
	
	// 上传文件
	protected File uploadFile;
	// 文件名
	protected String fileName;
	// 下载用 返回的文件流
	protected InputStream returnStream;
	// 下载用的名字
	protected String downFileName;
	// 附件表ID
	private String id;
	
	// 
	private FileService fileService;
	
	// 附件列表
	private List<TFile> fileList;
	

	/**
	 * 上传文件
	 */
	public String upload() throws Exception {

		// 判断文件大小 不大于10M
		if (fileName == null
				|| uploadFile == null || (uploadFile.length() > IConstant.FILE_BUFFER_SIZE
						* IConstant.FILE_SIZE_TEN * IConstant.FILE_SIZE_HUNDRED)) {
			super.setInfo("上传失败，附件不能超过1M");//OUTOFSIZE
			return "UPLOAD_SUCCESS";
		}

		// 文件存到服务器的名字
		String saveFileName = FileUtils.getFileName(fileName)
				+ "_"
				+ DateFormatTool.format(new Date(), true).replace(" ", "")
						.replaceAll("-", "").replaceAll(":", "")
				+ FileUtils.getExtention(fileName);
		
		//String path = Resources.getString((String)super.getSession().getAttribute("uploadpath"), "struts");
      String path = Resources.getString("uploadpath", "struts");
		if ("EXCEPTION_STRING".equals(path)) {
			super.setInfo("没有指定上传路径");//PATHERROR
			return "UPLOAD_SUCCESS";
		}

		FileUtils.createFolder(path);

		// 创建一个文件
		File saveFile = new File(path + saveFileName);

		String s = saveFileName;

		try {

			// 上传文件
			org.apache.commons.io.FileUtils.copyFile(uploadFile, saveFile);

			TFile entity = new TFile();
			entity.setUrl(path);
			entity.setTableid(Long.parseLong((String)super.getSession().getAttribute("tableid")));
			entity.setColname((String)super.getSession().getAttribute("colname"));
			entity.setFilename(fileName);
			entity.setRealfilename(saveFileName);
			entity.setOperuser(((TUser) super.getSession().getAttribute(
					IConstant.SESSION_TUSER)).getId());
			entity.setOperdate(DateFormatTool.formatToDate(fileService
					.getSysdate("yyyy-MM-dd HH24:mi"), true));
			
			// 是否是图片
			if (IConstant.IMAGE_TYPE.indexOf(FileUtils.getExtention(fileName).toUpperCase()) != -1) {
				entity.setImageflag("1");
			} else {
				entity.setImageflag("0");
			}

			this.fileService.saveFile(entity);
			
			this.fileList = fileService.findListByHql(" from TFile where tableid = '" + super.getSession().getAttribute("tableid") + "' and colname = '" + super.getSession().getAttribute("colname") + "'");

			// 上传后信息
			super.setInfo("上传成功");
			
			return "UPLOAD_SUCCESS";

		} catch (Exception e) {
			// 上传后信息
			super.setInfo(s);
			s = "文件上传出现错误";
			throw new AppException("上传失败");
		}

	}
	
	/**
	 * 下载
	 * 
	 * @throws FileNotFoundException
	 */
	public String fileDownload() throws AppException, FileNotFoundException {

		TFile entity = (TFile) fileService.findById(Long
				.parseLong(this.id), TFile.class.getName());

		returnStream = new java.io.FileInputStream(entity.getUrl() + entity.getRealfilename());

		downFileName = entity.getFilename();
		
		return "DOWNLOAD_SUCCESS";

	}

	/**
	 * 删除文件
	 */
	public void fileDelete() throws Exception {

		TFile entity = (TFile) fileService.findById(Long
				.parseLong(this.id), TFile.class.getName());

		// 删除文件
		File f = new File(entity.getUrl() + entity.getRealfilename());
		
		if (f.exists()) {
			f.delete();
		}

		// 删除数据库
		this.fileService.deleteFile(Long.parseLong(id));

	}

	/**
	 * 下载时需要显示的名字
	 */
	public String getDownloadFileName() throws Exception {

		downFileName = new String(downFileName.getBytes(), "ISO8859-1");

		return downFileName;

	}
	
	/**
	 * 显示图片
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public String showImage() throws Exception {
		
		TFile entity = (TFile) fileService.findById(Long
				.parseLong(this.id), TFile.class.getName());

		returnStream = new java.io.FileInputStream(entity.getUrl() + entity.getRealfilename());
		
		return "PNG_SUCCESS";

	}
	
	/**
	 * 附件列表
	 * @return
	 * @throws AppException
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	public String getFileListByTableid() throws AppException {
		
		this.fileList = fileService.findListByHql(" from TFile where tableid = '" + super.getSession().getAttribute("tableid") + "' and colname = '" + super.getSession().getAttribute("colname") + "'");
		
		if (super.getRequest().getParameter("type") == null) {
			return "FILELIST_SUCCESS";
		} else {
			return "FILELIST_READONLY_SUCCESS";
		}
		
	}	

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getReturnStream() {
		return returnStream;
	}

	public void setReturnStream(InputStream returnStream) {
		this.returnStream = returnStream;
	}

	public String getDownFileName() {
		return downFileName;
	}

	public void setDownFileName(String downFileName) {
		this.downFileName = downFileName;
	}
	
	public void setUploadFileFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<TFile> getFileList() {
		return fileList;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}
	
}
